<?php
/**
 * Created by PhpStorm.
 * User: jiangfb
 * Date: 2016/9/22
 * Time: 15:06
 */

namespace common\repositories\userauth;

use common\entities\ConfigEntity;
use common\entities\myhtsq\MyscrmParttimeBusinessEntity;
use common\entities\myhtsq\RoleUserEntity;
use Yii;
use common\repositories\BaseRepository;
use common\entities\myhtsq\RoleEntity;
use common\entities\myhtsq\ActionPackageEntity;
use common\entities\myhtsq\ErpBusinessUnitEntity;
use yii\db\Query;
use yii\helpers\ArrayHelper;

class UserAuthRepository extends BaseRepository
{
    public function addRole($data)
    {
        $roleEntity = new RoleEntity();
        $roleEntity->role_name = $data["role_name"];
        $roleEntity->parent_id = $data["parent_id"];
        $roleEntity->remart_text = $data["remart_text"] ? $data["remart_text"] : "";
        $roleEntity->organization_id = 1;
        return $roleEntity->save();
    }

    public function saveRole($data)
    {
        $roleEntity = RoleEntity::find()->where(['role_id' => $data['role_id']])->one();
        if (empty($roleEntity)){
            return false;
        }
        $roleEntity->role_name = $data["role_name"];
        $roleEntity->parent_id = $data["parent_id"];
        $roleEntity->remart_text = $data["remart_text"] ? $data["remart_text"] : "";
        $roleEntity->organization_id = 1;
        return $roleEntity->save();
    }

    public function deleteRole($role_id){
        $roleEntity = RoleEntity::find()->where(['role_id' => $role_id])->one();
        if (empty($roleEntity)){
            return false;
        }
        return $roleEntity->delete();
    }

    public function getRoleList($keyword)
    {
        if (empty($keyword)){
            $blocList = RoleEntity::find()->select('role_id,role_name,remart_text,parent_id')->where(['parent_id' => -1])->asArray()->all();
            $companyList =  RoleEntity::find()->select('role_id,role_name,remart_text,parent_id')->where(['parent_id' => 0])->asArray()->all();
        }else{
            $blocList = RoleEntity::find()->select('role_id,role_name,remart_text,parent_id')->where(['parent_id' => -1])->andWhere(['like', 'role_name', $keyword])->asArray()->all();
            $companyList = RoleEntity::find()->select('role_id,role_name,remart_text,parent_id')->where(['parent_id' => 0])->andWhere(['like', 'role_name', $keyword])->asArray()->all();
        }

        return ['group' => $blocList, 'company' => $companyList];

    }

    public function getRoleInfoById($role_id)
    {
        return RoleEntity::find()->select('role_id,role_name,parent_id,remart_text')->where(['role_id'=>$role_id])->one();
    }

    public function getAuthList()
    {
        $authlist = ActionPackageEntity::find()->select('action_package_id,name,parent_id')->where(['parent_id' => null])->asArray()->all();

        foreach($authlist as $k => $v){
            $authlist[$k]['sub'] = ActionPackageEntity::find()
                ->select('action_package_id,name,parent_id')
                ->where(['parent_id' => $v['action_package_id']])
                ->asArray()
                ->all();
        }
        foreach ($authlist as $k => $v){
            if (empty($v['sub'])){
                $actionList = $this->getAuthListByPackageId($v['action_package_id']);
                if (!empty($actionList[0]['action_id'])){
                    $authlist[$k]['actions'] = $actionList;
                }else{
                    $authlist[$k]['actions'] = [];
                }

            }else{
                foreach ($v['sub'] as $i => $row){
                    $actionList = $this->getAuthListByPackageId($row['action_package_id']);
                    if (!empty($actionList[0]['action_id'])){
                        $authlist[$k]['sub'][$i]['actions'] = $actionList;
                    }else{
                        $authlist[$k]['sub'][$i]['actions'] = [];
                    }
                }
            }
        }

        return $authlist;
    }

    public function getAuthListByPackageId($packageId)
    {
        $query = new Query();
        $query->select('myscrm_action_package.action_package_id,myscrm_action.action_code,myscrm_action.name,myscrm_action.action_id')->from('myscrm_action_package')
            ->leftJoin('myscrm_action_package_relation','myscrm_action_package_relation.action_package_id=myscrm_action_package.action_package_id')
            ->leftJoin('myscrm_action','myscrm_action.action_id=myscrm_action_package_relation.action_id')
            ->where(['myscrm_action_package.action_package_id' => $packageId]);
        return $query->createCommand(ConfigEntity::getDb())->queryAll();
    }

    public function getOrgList()
    {
        $orgRoot = ErpBusinessUnitEntity::find()->select('BUGUID,BUName,ParentGUID')->where(['IsCompany' => 1, 'Level' => 0])->asArray()->all();
        $orgFirstLevel = ErpBusinessUnitEntity::find()->select('BUGUID,BUName,ParentGUID')->where(['IsCompany' => 1, 'Level' => 1])->asArray()->all();
        $orgSecondLevel = ErpBusinessUnitEntity::find()->select('BUGUID,BUName,ParentGUID')->where(['IsCompany' => 1, 'Level' => 2])->asArray()->all();
        $orgThirdLevel = ErpBusinessUnitEntity::find()->select('BUGUID,BUName,ParentGUID')->where(['IsCompany' => 1, 'Level' => 3])->asArray()->all();
        return $this->makeOrgTree($orgRoot,$this->makeOrgTree($orgFirstLevel,$this->makeOrgTree($orgSecondLevel,$orgThirdLevel)));
    }

    private function makeOrgTree($parendArray, $sonArray)
    {
        foreach($sonArray as $k => $son){
            foreach ($parendArray as $row => $parent){
                if ($son['ParentGUID'] == $parent['BUGUID']){
                    $parendArray[$row]['son'][] = $son;
                }
            }
        }
        return $parendArray;
    }

    public function getPartTimeBUList($userGuid)
    {
        $query = new Query();
        $query->select('myscrm_parttime_business.bu_guid,myscrm_erp_business_unit.BUName')->from('myscrm_parttime_business')
            ->leftJoin('myscrm_erp_business_unit','myscrm_parttime_business.bu_guid=myscrm_erp_business_unit.BUGUID')
            ->where(['myscrm_parttime_business.user_guid' => $userGuid]);
        return $query->createCommand(ConfigEntity::getDb())->queryAll();
    }

    public function setUserRole($userGUID, $roleList)
    {
        $sql = '';
        $operateUser = Yii::$app->user->identity->username;
        $connection = RoleUserEntity::getDb();
        $transaction = $connection->beginTransaction();
        try {
            RoleUserEntity::deleteAll(['user_id' => $userGUID]);
            foreach($roleList as $k => $v){
                $sql .= "INSERT INTO myscrm_role_user (role_id,user_id,created_by,modified_by) VALUES($v,'".$userGUID."','".$operateUser."','".$operateUser."'); ";
            }
            $connection->createCommand($sql)->execute();
            $transaction->commit();
            return true;
        } catch (\Exception $ex) {
            $transaction->rollBack();
            throw new \Exception($ex->getMessage());
        }

        return true;
    }

    public function setUserParttimeBU($userGUID,$partTimeBUGUIDList)
    {
        $sql = '';
        $operateUser = Yii::$app->user->identity->username;

        $connection = MyscrmParttimeBusinessEntity::getDb();
        $transaction = $connection->beginTransaction();
        try {
            MyscrmParttimeBusinessEntity::deleteAll(['user_guid' => $userGUID]);
            foreach($partTimeBUGUIDList as $k => $v){
                $sql .= "INSERT INTO myscrm_parttime_business (user_guid,bu_guid,created_by,created_time) VALUES('".$userGUID."','".$v."','".$operateUser."','".date('Y-m-d H:i:s')."'); ";
            }
            $connection->createCommand($sql)->execute();
            $transaction->commit();
            return true;
        } catch (\Exception $ex) {
            $transaction->rollBack();
            throw new \Exception($ex->getMessage());
        }

        return true;
    }

    /**
     * @return mixed
     */
    public function getCurrUserAuth()
    {
        $query = new Query();
        $authData = $query->select('myscrm_action.action_code')
            ->from('myscrm_role_user')
            ->leftJoin('myscrm_role_action','myscrm_role_user.role_id=myscrm_role_action.role_id')
            ->leftJoin('myscrm_action','myscrm_role_action.action_id=myscrm_action.action_id')
            ->where(['myscrm_role_user.user_id' => Yii::$app->user->identity->userguid])
            ->distinct()
            ->createCommand(ConfigEntity::getDb())->queryAll();
        return ArrayHelper::getColumn($authData, 'action_code');
    }

}


